public class MaximumSubarray {

    // 查找子数组之和的最大值
    public static int maxSubArraySum(int[] nums) {
        if (nums == null || nums.length == 0) {
            throw new IllegalArgumentException("数组不能为空");
        }

        int maxCurrent = nums[0];
        int maxGlobal = nums[0];

        for (int i = 1; i < nums.length; i++) {

            maxCurrent = Math.max(nums[i], maxCurrent + nums[i]);


            if (maxCurrent > maxGlobal) {
                maxGlobal = maxCurrent;
            }
        }

        return maxGlobal;
    }

    public static void main(String[] args) {

        int[] test1 = {1, -2, 3, 5, -1};
        int[] test2 = {1, -2, 3, -8, 5, 1};
        int[] test3 = {1, -2, 3, -2, 5, 1};
        int[] test4 = {-3, -1, -2};
        int[] test5 = {5};

        System.out.println("测试用例1结果: " + maxSubArraySum(test1));
        System.out.println("测试用例2结果: " + maxSubArraySum(test2));
        System.out.println("测试用例3结果: " + maxSubArraySum(test3));
        System.out.println("测试用例4结果: " + maxSubArraySum(test4));
        System.out.println("测试用例5结果: " + maxSubArraySum(test5));
    }
}